<?php
	
	class Smurly{
		
		function resolve($sv){
			if(!$sv) return NULL;
			$a = explode('.', $sv);
			$V = My();
			while(count($a)){
				if(!$a[0]) break;
				if(!is_object($V) || !is_callable(array($V, 'get'))){
					if(!is_scalar($V)) break;
					// you're trying to access a property of a scalar value, so we'll make it a Jstring
					$V = new Jstring($V);
				}
				if(is_null($v = $V->get($a[0]))) break;
				$V = $v;
				array_shift($a);
			}
			return (count($a)) ? NULL : $V;
		}
		
		function run($s){
			$ms = $this->match_all($s);
			foreach($ms as $m){
				if($m[1]){
					My()->put(substr($m[1], 1, -1), $this->resolve($m[2]));
					$s = $this->replace($m[1].$m[2], '', $s);
				}else{
					if(!is_null($v = $this->resolve($m[2]))) $s = $this->replace($m[2], $v, $s);
				}
			}
			return $s;		
		}
		
		function match_all($s){
			preg_match_all('/\{(\@[a-zA-Z0-9_]+\=)?([a-zA-Z0-9_\.]+)\}/', $s, $ms, PREG_SET_ORDER);
			return $ms;
		}
		
		function replace($sm, $v, $s){
			return preg_replace('/\{('.$sm.')\}/', $v, $s, 1);
		}
		
		function replace_all($sm, $v, $s){
			return str_replace('{'.$sm.'}', $v, $s);
		}		
	}
